package com.zhixinhuixue.zsyte.xxx.ui.activity

import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.view.KeyEvent
import android.widget.CompoundButton
import android.widget.Toast
import androidx.lifecycle.Observer
import com.scandecode.ScanDecode
import com.scandecode.inf.ScanInterface
import com.scandecode.inf.ScanInterface.OnScanListener
import com.zhixinhuixue.zsyte.xxx.R
import com.zhixinhuixue.zsyte.xxx.app.api.NetUrl
import com.zhixinhuixue.zsyte.xxx.app.base.BaseActivity
import com.zhixinhuixue.zsyte.xxx.app.ext.initBack
import com.zhixinhuixue.zsyte.xxx.databinding.ActivityWlsjBinding
import com.zhixinhuixue.zsyte.xxx.ui.viewmodel.WLSJViewModel
import me.hgj.mvvmhelper.ext.*
import me.hgj.mvvmhelper.net.LoadStatusEntity
import me.hgj.mvvmhelper.widget.state.InputWidgetDialog
import java.util.*


/**
 * 作者　: hegaojian
 * 时间　: 2020/11/18
 * 描述　: 虽然在Activity代码少了，但是DataBinding 不太好用
 */
class WLSJActivity : BaseActivity<WLSJViewModel, ActivityWlsjBinding>() {

    private var scanDecode: ScanInterface? = null
    override fun initView(savedInstanceState: Bundle?) {
        //初始化toolbar
        mToolbar.initBack("提交数据") {
            finish()
        }

        mDataBind.viewModel = mViewModel
        mDataBind.click = LoginClickProxy()

        try {
            initScanner()
        } catch (e: Exception) {

        }

        mDataBind.radioGroup.check(R.id.radioButton1)
        mDataBind.radioGroup.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.radioButton4 -> {
                    mDataBind.viewSn.gone()
                    mDataBind.edtJwh.text = "888888"
                }
                else -> {
                    mDataBind.viewSn.visible()
                    mDataBind.edtJwh.text = ""
                }
            }
        }
    }

    private var count = 0
    private fun initScanner() {
        scanDecode = ScanDecode(this)
        scanDecode?.initService("true")
        scanDecode?.getBarCode(object : OnScanListener {
            override fun getBarcode(data: String) {
                if (mDataBind.edtCus.text.toString().isEmpty()) {
                    showMsg("请输入客户ID")
                    return
                }
                if (mDataBind.radioGroup.checkedRadioButtonId == R.id.radioButton4) {
                    mDataBind.edtJwh.text = "888888"
                    mDataBind.edtLpb.text = data
                    Handler().postDelayed({
                        postData()
                    }, 300) //延迟10秒执行
                } else {
                    if (TextUtils.isEmpty(mDataBind.edtJwh.text.toString())) {
                        mDataBind.edtJwh.text = data

                    } else {
                        if (mDataBind.radioGroup.checkedRadioButtonId == R.id.radioButton2) {
                            count += 1
                            if (count == 1) {
                                mDataBind.edtLpb.setText(data)

                            } else if (count == 2) {
                                var textString = mDataBind.edtLpb.text.toString()
                                mDataBind.edtLpb.setText(textString + "\r\n" + data)

                                Handler().postDelayed({
                                    postData()
                                }, 300) //延迟10秒执行
                            }
                        } else {
                            mDataBind.edtLpb.setText(data)

                            Handler().postDelayed({
                                postData()
                            }, 300) //延迟10秒执行
                        }


                    }
                }

            }


            override fun getBarcodeByte(bytes: ByteArray) {}
        })
    }


    /**
     * 请求成功
     */
    override fun onRequestSuccess() {
        //监听登录结果
        mViewModel.loginData.observe(this, Observer {
            runOnUiThread {

                mDataBind.tvSuccess.visible()
                mDataBind.tvError.gone()
                mDataBind.edtJwh.text = ""
                mDataBind.edtLpb.text = ""
                count = 0

            }


        })
    }

    /**
     * 请求失败
     * @param loadStatus LoadStatusEntity
     */
    override fun onRequestError(loadStatus: LoadStatusEntity) {
        when (loadStatus.requestCode) {
            NetUrl.WULIAOSHANGJIA -> {
                mDataBind.tvSuccess.gone()
                mDataBind.tvError.visible()
                when (loadStatus.errorMessage) {
                    "ktxtm repeat" -> mDataBind.tvError.text = "箱号重复"
                    "SN repeat" -> mDataBind.tvError.text = "SN重复"
                    else -> loadStatus.errorMessage
                }
                count = 0
                mDataBind.edtJwh.text = ""
                mDataBind.edtLpb.text = ""

            }
        }
    }

    inner class LoginClickProxy {

        fun clear() {
            mDataBind.edtJwh.text=""

        }
        fun clear1() {
            mDataBind.edtLpb.text=""
        }
        //登录
        fun login() {
            postData()
        }

        fun cus_id() {
            val widgetDialog = InputWidgetDialog(this@WLSJActivity)
            widgetDialog.show()
            widgetDialog.setInputHint("请输入客户ID")
            widgetDialog.setDefaultInput(mDataBind.edtCus.textString())
            widgetDialog.setClickListener { type ->
                if (type == 1) {
                    widgetDialog.cancel()
                } else if (type == 2) {
                    mDataBind.edtCus.text = widgetDialog.inputContent
                }
                widgetDialog.cancel()
            }
        }

        var onCheckedChangeListener =
            CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
                mViewModel.isShowPwd.set(isChecked)
            }
    }

    private fun postData() {
        var str = ""
        when (mDataBind.radioGroup.checkedRadioButtonId) {
            R.id.radioButton1 -> str = "1"
            R.id.radioButton2 -> str = "2"
            R.id.radioButton3 -> str = "3"
            R.id.radioButton4 -> str = "4"
            else -> ""
        }
        when {
            mDataBind.edtJwh.text.toString().isEmpty() -> showMsg("请扫描箱号")
            mDataBind.edtLpb.text.toString().isEmpty() -> showMsg("请扫描SN")
            str.isEmpty() -> showMsg("请选择箱类型")
            else -> {
                var datas = mDataBind.edtLpb.text.toString().replace("\r\n".toRegex(), ",")
                datas = datas.replace("，".toRegex(), ",")
                datas = datas.replace("\n".toRegex(), ",")
                datas = datas.replace("\r".toRegex(), ",")
                datas = datas.replace("\t".toRegex(), ",")
                datas = datas.replace(" ".toRegex(), ",")

                if (!TextUtils.isEmpty(datas) && datas.endsWith(",")) {
                    datas = datas.substring(0, datas.length - 1)
                }

                if (datas.contains(mDataBind.edtJwh.text.toString())) {
                    showMsg("箱号和SN重复")
                    return
                }

                mViewModel.wlsj(
                    mDataBind.edtCus.text.toString(),
                    mDataBind.edtJwh.text.toString(),
                    datas,
                    str
                )
            }
        }

    }

    private fun showMsg(msg: String) {
        mDataBind.tvSuccess.gone()
        mDataBind.tvError.visible()
        mDataBind.tvError.text = msg
    }

    override fun onDestroy() {
        try {
            scanDecode!!.stopScan()
            scanDecode!!.onDestroy()
        } catch (e: Exception) {

        }

        super.onDestroy()
    }

    private var firstTime: Long = 0

    /**
     * 第二种办法
     * @param keyCode
     * @param event
     * @return
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            val secondTime = System.currentTimeMillis()
            if (secondTime - firstTime > 2000) {
                Toast.makeText(this@WLSJActivity, "再按一次退出程序", Toast.LENGTH_SHORT).show()
                firstTime = secondTime
                return true
            } else {
                System.exit(0)
            }
        }
        return super.onKeyDown(keyCode, event)
    }


}